const { PostItem, User, CommentItem } = require('../db')
// const { col } = require('sequelize');

//根据postId 分页获取评论
exports.getCommentsByPostId = async (req, res) => {
    try {
        const { postId, page = 1, pageSize = 10 } = req.query;
        const skip = (page - 1) * pageSize;

        // 查询没有 parentId 的一级评论
        const rootComments = await CommentItem.findAndCountAll({
            where: { postId, parentId: null },
            include: [
                {
                    model: User,
                    attributes: ['username', 'avatarUrl']
                }
            ],
            limit: parseInt(pageSize),
            offset: skip,
            order: [['createdAt', 'DESC']]
        });

        // 获取所有一级评论的ID
        const rootCommentIds = rootComments.rows.map(comment => comment.id);

        // 查询所有回复（二级评论）
        const replies = await CommentItem.findAll({
            where: { parentId: rootCommentIds },
            include: [
                {
                    model: User,
                    attributes: ['username', 'avatarUrl']
                }
            ],
            order: [['createdAt', 'ASC']]
        });

        // 创建一个以评论ID为键的一级评论对象映射
        const rootCommentsMap = rootComments.rows.reduce((map, comment) => {
            map[comment.id] = comment.get({ plain: true }); // 转换为普通对象
            map[comment.id].reply = []; // 初始化 reply 数组
            return map;
        }, {});

        // 将回复添加到对应的一级评论的reply数组中
        replies.forEach(reply => {
            if (rootCommentsMap[reply.parentId]) {
                rootCommentsMap[reply.parentId].reply.push(reply.get({ plain: true })); // 转换为普通对象
            }
        });


        res.send({
            status: 200,
            comments: Object.values(rootCommentsMap) // 确保发送的是普通对象数组
        });
    } catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}
// 根据commentId获取子评论
exports.getCommentsByCommentId = async (req, res) => {
    try {
        const { commentId, page = 1, pageSize = 10 } = req.query
        const skip = (page - 1) * pageSize
        const comments = await CommentItem.findAndCountAll({
            where: { parentId: commentId },
            limit: pageSize,
            offset: skip,
            order: [['createdAt', 'DESC']] // 按创建时间降序排列
        })


        res.send({
            status: 200,
            comments
        })
    }
    catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}

// 根据postId新建评论
exports.createComment = async (req, res) => {
    try {
        const { postId, content, parentId } = req.body
        const { id: UserId } = req.user
        const comment = await CommentItem.create({
            postId,
            content,
            UserId,
            parentId,
            date: new Date().toISOString().slice(0, 10).replace(/-/g, '年').replace(/-/g, '月') + '日',
        })
        res.send({
            status: 200,
            comment
        })
    }
    catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}

//删除自己的评论
exports.deleteComment = async (req, res) => {
    try {
        const { commentId } = req.body
        const comment = await CommentItem.findByPk(commentId)
        if (!comment) {
            res.status(404).send('评论不存在')
        }
        else {
            await comment.destroy()
            res.send({
                status: 200,
                message: '删除成功'
            })
        }
    } catch (err) {

    }
}